﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.ApplicationBlocks.Data;
using System.Configuration;

using BE;
using BC;

namespace ModuleDuoc
{
    public partial class frmHD_BanLe : ModuleDuoc.Base.frmBase
    {
        //DataTable dt;
        string _tennhanvien = "Nguyễn Văn A";
        string _maphongban = "02";
        string _manv = "nguyentheson1";
        string _donhang = "theodon";
        int _err;
        private static string _loaiPhieu;
        string sql;
        int num1;
        int num2;


        //delegate
        public delegate void SetDGV(DataGridView dgv);
        public SetDGV MySetDgv;
        public delegate void SetStr(String str1, String str2, String tongtien, String khachdua); //str1: ten, str2: dia chi
        public SetStr MySetStr;

        public frmHD_BanLe()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            this.pnlContent.Enabled = true;
            this.cboxGioiTinh.Text = "Nam";
            
        }
        // ---------------delegate hủy hàng-----------------
        public void GetValue(String str1)
        {
            // khai báo 1 hàm với tham số đầu vào là str1, nó sẽ đưa dữ liệu vào txt
            this.txtDelegate.Text = str1;
        }
        // ---------------delegate Trả lại hàng-----------------
        public void GetTraLai(String _SoLuong, String _LyDo)
        {
            // khai báo 1 hàm với tham số đầu vào là str1, nó sẽ đưa dữ liệu vào txt
            //this.txtDelegateTraLai_SL.Text = "";
            this.txtDelegateTraLai_SL.Text = _SoLuong;
            this.txtDelegateTraLai_GC.Text = _LyDo;
        }
        public frmHD_BanLe(string tennhanvien, string maphongban)
        {
            InitializeComponent();
            _tennhanvien = tennhanvien;
            _maphongban = maphongban;
        }
        public frmHD_BanLe(string tennhanvien, string maphongban, string manhanvien)
        {
            InitializeComponent();
            _tennhanvien = tennhanvien;//la ten nhan vien
            _maphongban = maphongban;
            _manv = manhanvien;
        }
        public frmHD_BanLe(string donhang)
        {
            InitializeComponent();
            _donhang = donhang;
        }
        private void frmHD_BanLe_Load(object sender, EventArgs e)
        {
            _loaiPhieu = "3";
            this.txtMaDon.Focus();
            dgvData.AutoGenerateColumns = false;
            this.lblTitle.Text = "PHIẾU XUẤT HÀNG";
            this.loadSoPhieu();
            txtNhanVien.Text = _tennhanvien;
            //this.btnSave.Enabled = false;
            if (dgvLeft.Rows.Count > 0)
            { itmSua.Visible = true; }

            setPermission();
        }
        private void setTab(Control c, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                c.Focus();
            }
        }

        private void loadSoPhieu()
        {
            //string sql = "SELECT sophieu FROM zD_PHIEUXUATKHO ";
            string sql = "SELECT sophieu, ngaylap, id FROM zD_PHIEUXUATKHO WHERE loaiphieu = '" + _loaiPhieu +"' and huy = 0 and ngaylap BETWEEN '" + this.date1.Value.ToString("MM/dd/yyyy 00:00:00") + "' AND '" + this.date2.Value.ToString("MM/dd/yyyy 23:59:59") + "' ORDER BY ngaylap desc,sophieu, id";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.dgvLeft.DataSource = dt;
            this.btnSoLuong.Text = "Số lượng:" + dt.Rows.Count;
        }

        private void txtCK_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtCKTM_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtDienThoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtTuoi_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        
        private void txtVAT_TextChanged(object sender, EventArgs e)
        {
            //400 + 5*400/100
            Double sl;
            Double dg;
            Double vat;
            Double tt;

            try
            {
                sl = Double.Parse(this.txtSL.Text);
                dg = Double.Parse(this.txtDonGia.Text);
                vat = Double.Parse(this.txtVAT.Text);

                tt = (sl * dg) + (sl * dg) * vat / 100;
                //String.Format("{0:0,0 vnđ}", 20000000)
                this.txtThanhTien.Text = String.Format("{0:0,0}", tt);
            }
            catch (Exception)
            { }
        }

        private void txtCongTong_TextChanged(object sender, EventArgs e)
        {
            this.txtTongTien.Text = this.txtCongTong.Text;
            this.txtCKTM.Text = "";
            this.txtCK.Text = "";
        }

        private void txtCK_TextChanged(object sender, EventArgs e)
        {
            this.txtCKTM.Text = "";
            Double tc;
            Double ck;//Triet khau %
            Double tt;
            try
            {
                tc = Double.Parse(this.txtCongTong.Text);
                if (this.txtCK.Text != "")
                {
                    ck = Double.Parse(this.txtCK.Text);
                }
                else
                {
                    ck = 0;
                }
                tt = tc - tc * ck / 100;
                //String.Format("{0:0,0 vnđ}", 20000000)
                this.txtTongTien.Text = String.Format("{0:0,0}", tt);
            }
            catch (Exception)
            { }
        }

        private void txtCKTM_TextChanged(object sender, EventArgs e)
        {
            this.txtCK.Text = "";
            Double tc = 0;
            Double cktm = 0;
            Double tt = 0;
            try
            {
                tc = Double.Parse(this.txtCongTong.Text);
                if (this.txtCKTM.Text != "")
                {
                    cktm = Double.Parse(this.txtCKTM.Text);
                }
                else
                {
                    cktm = 0;
                }
                tt = tc - cktm;
                //String.Format("{0:0,0 vnđ}", 20000000)
                this.txtTongTien.Text = String.Format("{0:0,0}", tt);
            }
            catch (Exception)
            { }

        }
        public override void btnThemMoi_Click(object sender, EventArgs e)
        {
            this.txtNhanVien.Text = _tennhanvien;
            this.cboxChonNgay.Visible = true;
            //this.dgvData.Columns["tralai"].Visible = false;
            base.btnThemMoi_Click(sender, e);
            this.clear();
            this.txtId.Text = "";
            this.itmSua.Visible = false;

        }
        private void clear1()
        {
           this.txtMaDon.Text = "";
            this.txtSID.Text = "";
            this.txtTenKH.Text = "";
            this.txtDiaChi.Text = "";
            this.txtDienThoai.Text = "";
            this.txtBacSiKeDon.Text = "";
        }
        private void clear()
        {
            this.txtMaVach.Enabled = true;
            this.txtSL.Enabled = true;
            this.txtTenThuoc.Enabled = true;
            this.pnlContent.Enabled = true;
            this.groupBox2.Enabled = true;
            this.panel3.Enabled = true;
            this.dgvData.Enabled = true;
            this.groupBox1.Enabled = true;

            this.dgvData.Rows.Clear();
            this.txtSID.SelectAll();
            this.txtMaDon.Focus();
            this.txtMaDon.Text = "";

            //thanh toan
            this.txtCongTong.Text = "";
            this.txtTongTien.Text = "";
            this.txtTongVAT.Text = "";
            this.txtTraLai.Text = "";
            this.txtKhachDua.Text = "";
            this.txtCKTM.Text = "";
            this.txtCK.Text = "";
            this.txtGhiChu.Text = "";
            this.txtSID.Text = "";
            this.txtTenKH.Text = "";
            this.txtDiaChi.Text = "";
            this.txtDienThoai.Text = "";
            this.txtBacSiKeDon.Text = "";
        }
        private string getSophieu()
        {
            string sql = "select isnull(max(id),0) as [MAX] from zD_PHIEUXUATKHO";
            DataTable dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                //return "HDBL-" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day + "-" + (int.Parse(dt.Rows[0]["MAX"].ToString()) + 1).ToString();
                return "HDBL-" + getTimeServer().ToString() + "-" + (int.Parse(dt.Rows[0]["MAX"].ToString()) + 1).ToString();
            }
            else
            {
                return "HDBL-0";
            }
        }

        private string getTimeServer()
        {
            string sql = "select * from hien_TimeServer";
            DataTable dt1 = new DataTable();
            dt1 = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt1.Rows.Count > 0)
            {
                return dt1.Rows[0][0].ToString();
            }
            else
            {
                return "Không kết nối được máy chủ";
            }
        }
        //Lây thời gian dạng: 2013-05-13 15:53:05 từ server
        private string getTimeServer2()
        {
            string sql = "SELECT [Expr1] FROM [QUANLYVTXN].[thongke].[hien_TimeServer2]";
            DataTable dt2 = new DataTable();
            dt2 = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt2.Rows.Count > 0)
            {
                return dt2.Rows[0][0].ToString();
            }
            else
            {
                return "Không kết nối được máy chủ";
            }
        }
        private string getTimeBy_SoPhieu()
        {
            string sql = "SELECT ngaylap FROM zD_PHIEUXUATKHO WHERE ngaylap = '" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", dgvLeft.CurrentRow.Cells["NgayLap"].Value) + "'";
            DataTable dt3 = new DataTable();
            dt3 = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt3.Rows.Count > 0)
            {
                return dt3.Rows[0][0].ToString();
            }
            else
            {
                return "Lỗi lấy thời gian từ số phiếu";
            }
        }

        public override void btnSave_Click(object sender, EventArgs e)
        {
            base.btnSave_Click(sender, e);
            if (this.groupBox2.Enabled == true)
            {
                if (this.txtId.Text == "")
                {
                    if (dgvData.Rows.Count > 0)
                    {
                        this.checkMaVach_SL();
                        if (_err == 0)
                        {
                            this.insertPhieu();
                            this.dgvData.Rows.Clear();
                            this.hide_viewDonHang();
                            this.clear();
                            this.txtId.Text = "";
                        }
                        else
                        {
                            MessageBox.Show("Số lượng thuốc hoặc mã vạch nhập không hợp lệ!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Không có dữ liệu!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.txtMaVach.Focus();
                    }
                }
                else
                {
                    if (this.txtLoaiPhieu.Text == "10")// loai phieu = 10 tuong duong khoa phieu
                    {
                        MessageBox.Show("Phiếu đã bị khóa nên không thể sửa được!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        updateChiTietPhieu();
                        updatePhieu();
                        MessageBox.Show("Cập nhật thành công!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.hide_viewDonHang();
                        this.dgvData.Rows.Clear();
                        this.clear();
                        this.txtId.Text = "";
                    }
                }
            }
            this.loadSoPhieu();
        }
        private int checkMaVach_SL()
        {
            _err = 0;
            try
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    try
                    {
                        Int32.Parse(this.dgvData.Rows[i].Cells["mavach"].Value.ToString());
                        Int32.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString());
                    }
                    catch (Exception)
                    {
                        return _err++;
                    }

                    if (this.dgvData.Rows[i].Cells["mavach"].Value.ToString() == "" || this.dgvData.Rows[i].Cells["soluong"].Value.ToString() == "")
                    {
                        return _err++;
                    }
                }
            }
            catch (Exception)
            { }
            return _err;
        }
        private void insertPhieu()
        {
            if (this.txtGhiChu.Text.Length > 100)
            {
                MessageBox.Show("Ghi chú quá dài!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtGhiChu.Focus();
            }
            else
            {
                try
                {
                    ZD_PHIEUXUATKHO obj = new ZD_PHIEUXUATKHO();
                    ZD_PHIEUXUATKHOBC bc = new ZD_PHIEUXUATKHOBC();
                    this.txtSoPhieu.Text = this.getSophieu();
                    obj.Sophieu = this.txtSoPhieu.Text;
                    //Neu lon hon ngay hien tai
                    if (DateTime.Compare(DateTime.Parse(this.cboxChonNgay.Text), DateTime.Now) > 0)
                    {
                        MessageBox.Show("Ngày không hợp lệ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        obj.Ngaylap = DateTime.Parse(cboxChonNgay.Text + " " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);

                        obj.Manhanvien = _tennhanvien;
                        //obj.Machinhanh = "100";
                        obj.Maphongban = _maphongban;
                        obj.Ghichu = this.txtGhiChu.Text;
                        obj.Tongtien = Double.Parse(this.txtTongTien.Text);
                        obj.Huy = false;
                        if (radBanLe.Checked == true)
                        {
                            obj.Loaiphieu = 3;//3: tuong ung voi hoa don ban le
                        }
                        else if (radNoiBo.Checked == true)
                        {
                            obj.Loaiphieu = 4;//4: tuong ung voi hoa don ban le
                        }
                        else if (radBaoHiem.Checked == true)
                        {
                            obj.Loaiphieu = 5;//5: tuong ung voi hoa don ban le
                        }
                        obj.Hoten = this.txtTenKH.Text;
                        obj.Diachi = this.txtDiaChi.Text;
                        obj.Dienthoai = this.txtDienThoai.Text;
                        if (this.cboxGioiTinh.Text == "Nam")
                        {
                            obj.Gioitinh = true;
                        }
                        else
                        {

                            obj.Gioitinh = false;
                        }
                        //obj.Nguoilinh = "";
                        //obj.Phonglinh = "";
                        obj.Printed = false;
                        if (this.txtTenKH.Text == "")
                        {
                            this.txtSID.Text = "BL";
                        }
                        else
                        {
                            obj.SID = this.txtSID.Text;
                        }
                        obj.DateSID = dateTimeSID.Value;
                        if (this.txtMaDon.Text != "")
                        {
                            obj.DonThuocID = Int32.Parse(this.txtMaDon.Text);
                        }
                        bc.Insert(obj);
                        insertChiTietPhieu();
                        if (MessageBox.Show("Thêm mới thành công! Bạn có muốn in phiếu này không?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            this.printReport();
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Lỗi thêm HĐBL!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void updatePhieu()
        {
            if (this.txtGhiChu.Text.Length > 100)
            {
                MessageBox.Show("Ghi chú quá dài!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtGhiChu.Focus();
            }
            else
            {
                try
                {
                    ZD_PHIEUXUATKHO obj = new ZD_PHIEUXUATKHO();
                    ZD_PHIEUXUATKHOBC bc = new ZD_PHIEUXUATKHOBC();
                    obj.Id = Int32.Parse(this.txtId.Text);
                    obj.Sophieu = this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString();
                    obj.Ngaylap = DateTime.Parse(this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["ngaylap"].Value.ToString());
                    obj.Manhanvien = _tennhanvien;
                    //obj.Machinhanh = "100";
                    obj.Maphongban = _maphongban;
                    obj.Ghichu = this.txtGhiChu.Text;
                    obj.Tongtien = Double.Parse(this.txtTongTien.Text);
                    obj.Huy = false;
                    obj.Loaiphieu = 3;//3: tuong ung voi hoa don ban le
                    obj.Hoten = this.txtTenKH.Text;
                    obj.Diachi = this.txtDiaChi.Text;
                    obj.Dienthoai = this.txtDienThoai.Text;
                    if (this.cboxGioiTinh.Text == "Nam")
                    {
                        obj.Gioitinh = true;
                    }
                    else
                    {

                        obj.Gioitinh = false;
                    }
                    //obj.Nguoilinh = "";
                    //obj.Phonglinh = "";
                    obj.Printed = false;
                    if (this.txtTenKH.Text == "")
                    {
                        this.txtSID.Text = "BL";
                    }
                    else
                    {
                        obj.SID = this.txtSID.Text;
                    }
                    obj.DateSID = dateTimeSID.Value;
                    try
                    {
                        obj.DonThuocID = Int32.Parse(this.txtMaDon.Text);
                    }
                    catch { }
                    bc.Update(obj);
                }
                catch (Exception)
                {
                    MessageBox.Show("Lỗi thêm HĐBL!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void printReport()
        {
            //string s = "HDBL-011012-34";
            string sql = "select * from hien_rpt_BanLe where sophieu='" + this.txtSoPhieu.Text + "'";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            frmShowReport frm = new frmShowReport(2);
            frmShowReport._thanhtien = lblBangChu.Text;
            frmShowReport._nhanvien = _tennhanvien;
            frmShowReport._tenKH = this.txtTenKH.Text;
            frmShowReport._diachiKH = this.txtDiaChi.Text;
            frmShowReport._dt = dt;
            frmShowReport.strC = frmShowReport.BC.HOADONBANLE;
            frm.ShowDialog();
        }
        private void insertChiTietPhieu()
        {
            try
            {
                ZD_PHIEUXUATKHOCTBC bc = new ZD_PHIEUXUATKHOCTBC();

                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    ZD_PHIEUXUATKHOCT obj = new ZD_PHIEUXUATKHOCT();
                    obj.Sophieu = this.txtSoPhieu.Text;
                    obj.Mavt = this.dgvData.Rows[i].Cells["mavt"].Value.ToString();
                    obj.Mavach = Int64.Parse(this.dgvData.Rows[i].Cells["mavach"].Value.ToString());
                    obj.Solo = this.dgvData.Rows[i].Cells["solo"].Value.ToString();
                    obj.Soluong = Double.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString());
                    obj.Dongia = Double.Parse(this.dgvData.Rows[i].Cells["dongia"].Value.ToString());
                    obj.Vat = Double.Parse(this.dgvData.Rows[i].Cells["vat"].Value.ToString());
                    obj.Thanhtien = Double.Parse(this.dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                    //try
                    //{
                    //    obj.DonthuocId = Int32.Parse(this.dgvData.Rows[i].Cells["donthuocid"].Value.ToString());
                    //}
                    //catch (Exception)
                    //{ }
                    //obj.Ngaysx = ;
                    //obj.Hansd = DateTime.Parse(this.dgvData.Rows[i].Cells["handung"].Value.ToString());
                    if (this.txtMaDon.Text != "")
                    {
                        obj.DonthuocId = Int32.Parse(this.txtMaDon.Text);
                    }
                    obj.Ghichu = this.txtGhiChu.Text;
                    if (obj.Soluong > 0)
                    {
                        obj.TraLai = 0;
                    }
                    else 
                    {
                        obj.TraLai = 2;
                    }

                    bc.Insert(obj);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi thêm chi tiết HĐBL!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void updateChiTietPhieu()
        {
            try
            {
                ZD_PHIEUXUATKHOCTBC bc = new ZD_PHIEUXUATKHOCTBC();

                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    ZD_PHIEUXUATKHOCT obj = new ZD_PHIEUXUATKHOCT();
                    obj.Id = Int32.Parse(this.dgvData.Rows[i].Cells["id1"].Value.ToString());
                    obj.Sophieu = dgvLeft.Rows[dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString();
                    obj.Mavt = this.dgvData.Rows[i].Cells["mavt"].Value.ToString();
                    obj.Mavach = Int64.Parse(this.dgvData.Rows[i].Cells["mavach"].Value.ToString());
                    obj.Solo = this.dgvData.Rows[i].Cells["solo"].Value.ToString();
                    obj.Soluong = Double.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString());
                    obj.Dongia = Double.Parse(this.dgvData.Rows[i].Cells["dongia"].Value.ToString());
                    obj.Vat = Double.Parse(this.dgvData.Rows[i].Cells["vat"].Value.ToString());
                    obj.Thanhtien = Double.Parse(this.dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                    try
                    {
                        obj.DonthuocId = Int32.Parse(this.dgvData.Rows[i].Cells["donthuocid"].Value.ToString());
                    }
                    catch (Exception)
                    { }
                    obj.Ghichu = this.txtDelegateTraLai_GC.Text;
                    obj.TraLai = Int32.Parse(this.dgvData.Rows[i].Cells["traLai"].Value.ToString());

                    bc.Update(obj);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi thêm chi tiết HĐBL!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtKhachDua_TextChanged(object sender, EventArgs e)
        {
            
            //this.txtKhachDua.Text = String.Format("{0:0,0}", Double.Parse(this.txtKhachDua.Text));
            try
            {
                if (Double.Parse(this.txtKhachDua.Text) - Double.Parse(this.txtTongTien.Text) < 0)
                {
                    this.label19.Text = "Thiếu";
                }
                else
                {
                    this.label19.Text = "Trả lại";
                }
            }
            catch (Exception)
            { }
            //Man hinh tinh tien
            //MySetStr(this.txtTenKH.Text, this.txtDiaChi.Text, this.txtTongTien.Text, this.txtKhachDua.Text);
            //MySetDgv(this.dgvData);
            Double kd;
            Double tl;
            Double tt;
            try
            {
                if (this.txtKhachDua.Text != "")
                {
                    kd = Double.Parse(this.txtKhachDua.Text);
                }
                else
                {
                    kd = 0;
                }
                tt = Double.Parse(this.txtTongTien.Text);
                tl = tt - kd;
                //String.Format("{0:0,0 vnđ}", 20000000)
                this.txtTraLai.Text = String.Format("{0:0,0}", tl);
            }
            catch (Exception)
            { }
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            this.txtVAT.Text = "0";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //if (Int32.Parse(txtSL.Text) <= Int32.Parse(txtTon.Text))
            {
                if (checkInput() == true & checkSP_DGV() == true)
                {
                    try
                    {
                        int mavach = Int32.Parse(this.txtMaVach.Text);
                        string tenthuoc = this.txtTenThuoc.Text;
                        string handung = this.txtHanDung.Text;
                        string solo = this.txtSoLo.Text;
                        string dvt = this.txtDVT.Text;
                        int soluong = Int32.Parse(this.txtSL.Text);
                        double dongia = Double.Parse(this.txtDonGia.Text);
                        double vat = Double.Parse(this.txtVAT.Text);
                        double thanhtien = Double.Parse(this.txtThanhTien.Text);
                        int mavt = Int32.Parse(this.txtmavt.Text);
                        int traLai = 0;
                        //int donThuocID = ;
                            
                        //this.dgvData.Rows.Add(this.txtMaVach.Text,this.txtTenThuoc.Text, this.txtHanDung.Text, this.txtSoLo.Text, this.txtDVT.Text, this.txtSL.Text, this.txtDonGia.Text, this.txtVAT.Text, this.txtThanhTien.Text, this.txtmavt.Text,"");
                        dgvData.Rows.Add(
                            mavach,
                            tenthuoc,
                            handung,
                            solo,
                            dvt,
                            soluong,
                            dongia,
                            vat,
                            thanhtien,
                            mavt,
                            traLai
                            );
                        getTongGia();

                        if (this.txtId.Text != "")
                        {
                            int i = this.dgvData.Rows.Count - 1;
                            ZD_PHIEUXUATKHOCTBC bc = new ZD_PHIEUXUATKHOCTBC();
                            ZD_PHIEUXUATKHOCT obj = new ZD_PHIEUXUATKHOCT();
                            obj.Sophieu = this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString();
                            obj.Mavt = this.dgvData.Rows[i].Cells["mavt"].Value.ToString();
                            obj.Mavach = Int64.Parse(this.dgvData.Rows[i].Cells["mavach"].Value.ToString());
                            obj.Solo = this.dgvData.Rows[i].Cells["solo"].Value.ToString();
                            obj.Soluong = Double.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString());
                            obj.Dongia = Double.Parse(this.dgvData.Rows[i].Cells["dongia"].Value.ToString());
                            obj.Vat = Double.Parse(this.dgvData.Rows[i].Cells["vat"].Value.ToString());
                            obj.Thanhtien = Double.Parse(this.dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
                            try
                            {
                                obj.DonthuocId = Int32.Parse(this.dgvData.Rows[i].Cells["donthuocid"].Value.ToString());
                            }
                            catch (Exception)
                            { }
                            obj.Ghichu = this.txtGhiChu.Text;
                            obj.TraLai = 0;

                            bc.Insert(obj);
                            this.selectTheoDoiBan();
                            //btnAdd_Click(sender, e);
                            btnSave_Click(sender, e);//update tổng tiền
                            //update tổng tiền
                        }
                    }
                    catch (Exception)
                    {}
                    this.txtTenThuoc.Text = "";
                    this.txtSL.Text = "";
                    this.txtMaVach.Text = "";
                }
            }
            //else
            //{
            //    MessageBox.Show("Số lượng không tồn âm nên không bán được thuốc này!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    txtSL.Focus();
            //}            
        }

        private void getTongGia()
        {
            Double vat = 0;
            Double tt = 0;
            for (int i = 0; i < this.dgvData.Rows.Count; i++)
            {
                vat += Double.Parse(this.dgvData.Rows[i].Cells["VAT"].Value.ToString());
                tt += Double.Parse(this.dgvData.Rows[i].Cells["thanhtien"].Value.ToString());
            }
            //this.txtTongVAT.Text = String.Format("{0:0,0}", vat);
            this.txtCongTong.Text = String.Format("{0:0,0}", tt);
        }
        private bool checkInput()
        {
            if (this.txtTenThuoc.Text == "")
            {
                MessageBox.Show("Tên thuốc không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtMaVach.Focus();
                return false;
            }
            else if (this.txtMaVach.Text == "")
            {
                MessageBox.Show("Mã vạch không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtMaVach.Focus();
                return false;
            }
            else if (this.txtSL.Text == "")
            {
                MessageBox.Show("Số lượng không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //this.txtSL.Focus();
                return false;
            }
            else if (this.txtGhiChu.Text.Length > 100)
            {
                MessageBox.Show("Ghi chú quá dài!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtGhiChu.Focus();
                return false;
            }
            return true;
        }
        private bool checkSP_DGV()
        {
            for (int i = 0; i < this.dgvData.Rows.Count; i++)
            {
                if (this.txtMaVach.Text == this.dgvData.Rows[i].Cells[0].Value.ToString())
                {
                    if (Int32.Parse(this.txtSL.Text.ToString()) > 0)
                    {
                        this.dgvData.Rows[i].Cells["soluong"].Value = Int32.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString()) + Int32.Parse(this.txtSL.Text.ToString());
                        this.tinhGia2();
                        return false;
                    }
                    this.tinhGia2();
                    //MessageBox.Show("Thuốc này đã được kê ở dưới rồi!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //this.txtMaVach.Focus();
                    //return false;
                }
            }
            return true;
        }

        private void txtSID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtSID_TextChanged(object sender, EventArgs e)
        {
            //try
            //{
            //    if (this.txtSID.Text.Substring(0, 1) == "0")
            //    {
            //        this.txtSID.Text = this.txtSID.Text.Substring(1);
            //    }
            //}
            //catch (Exception)
            //{ }
            //if (this.txtSID.Text.Length == 7)
            //{
            //    this.getInfoSID();//26092012
            //}
            //else
            //{
            //    this.txtTenKH.Text = "";
            //    this.txtTenKH.Enabled = true;
            //    this.txtDiaChi.Text = "";
            //    this.txtDiaChi.Enabled = true;
            //    this.txtDienThoai.Text = "";
            //    this.txtDienThoai.Enabled = true;
            //    this.cboxGioiTinh.Text = "Nam";
            //    this.cboxGioiTinh.Enabled = true;
            //}
        }
        private void getInfoSID()
        {
            try
            {
                //string sql = "select * from hien_BanLe where sophieu='" + this.txtSoPhieu.Text.Trim() + "'";
                string s = this.dateTimeSID.Text.Replace("/", "").Substring(0, 4) + this.dateTimeSID.Text.Replace("/", "").Substring(6, 2) + "-" + this.txtSID.Text;
                string sql = "SELECT PatientName, Sex, Age, [Address], Phone, PID FROM tbl_Patient WHERE [SID] ='" + s + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString01"], CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    this.txtTenKH.Text = dt.Rows[0]["PatientName"].ToString();
                    this.txtDiaChi.Text = dt.Rows[0]["Address"].ToString();
                    this.txtDienThoai.Text = dt.Rows[0]["Phone"].ToString();
                    if (dt.Rows[0]["Sex"].ToString() == "M")
                    {
                        this.cboxGioiTinh.Text = "Nam";
                    }
                    else
                    {
                        this.cboxGioiTinh.Text = "Nữ";
                    }
                    this.groupBox1.Enabled = false;
                    //this.txtSID.Enabled = true;
                }
                else
                {
                    MessageBox.Show("SID không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    
                }
            }
            catch (Exception)
            { }
        }

        private void txtMaVach_TextChanged(object sender, EventArgs e)
        {
            //if (this.txtMaVach.Text != "")
            //{
            //    this.getBy_MaVach();
            //    this.getBy_MaVach_TonKhoDuoc();
            //}
        }
        private void getBy_MaVach()
        {
            try
            {
                string sql = "select top 1 * from hien_Thuoc_PhieuNhapCT where maVach='" + this.txtMaVach.Text + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    //this.txtTenThuoc.Text = dt.Rows[0]["tenvt"].ToString() + "(" + dt.Rows[0]["Infoinclude"].ToString() + ")";
                    txtHanDung.Text = dt.Rows[0]["hansd"].ToString();
                    this.txtTenThuoc.Text = dt.Rows[0]["NameSearch"].ToString();
                    this.txtSoLo.Text = dt.Rows[0]["solo"].ToString();
                    this.txtDVT.Text = dt.Rows[0]["ten"].ToString();
                    this.txtDonGia.Text = dt.Rows[0]["giaban"].ToString();
                    this.txtVAT.Text = dt.Rows[0]["vat"].ToString();
                    this.txtmavt.Text = dt.Rows[0]["mavt"].ToString();
                    this.tinhGia();
                }
                else
                {
                    this.setNull();
                }
            }
            catch (Exception)
            { }
        }

        private void getBy_MaVach_BanTheoDon()
        {                
            try
            {
                int _mavach = Int32.Parse(this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["mavach"].Value.ToString());
                //string _tensp = this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tensp"].Value.ToString().IndexOf("(").ToString();
                //string _tensp = this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tenvt"].Value.ToString().Substring(0, this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tenvt"].Value.ToString().IndexOf("("));
                string _tensp = this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tenvt"].Value.ToString();
                string sql = "select top 1 * from hien_Thuoc_PhieuNhapCT where maVach='" + _mavach + "' and namesearch =N'" + _tensp + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    //this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tenvt"].Value = dt.Rows[0]["tenvt"].ToString() + "(" + dt.Rows[0]["Infoinclude"].ToString() + ")";
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tenvt"].Value = dt.Rows[0]["nameSearch"].ToString();
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["solo"].Value = dt.Rows[0]["solo"].ToString();
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["dvt"].Value = dt.Rows[0]["ten"].ToString();
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["dongia"].Value = String.Format("{0:0,0}",dt.Rows[0]["giaban"]);
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["vat"].Value = dt.Rows[0]["vat"].ToString();
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["mavt"].Value = dt.Rows[0]["mavt"].ToString();
                    //String.Format("{0:0,0}", tt)
                }
                else
                {
                    this.txtMaVach.Enabled = false;
                    this.txtTenThuoc.Enabled = false;
                    this.txtSL.Enabled = false;

                    MessageBox.Show("Không tin thấy mã vạch tương ứng!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["mavach"].Value = "";
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["solo"].Value = "";
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["dvt"].Value = dt.Rows[0]["ten"].ToString();
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["dongia"].Value = "0";
                    this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["vat"].Value = "0";
                }
            }
            catch (Exception)
            { }
        }

        private void setNull()
        {
            this.txtTenThuoc.Text = "";
            this.txtHanDung.Text = "";
            this.txtSoLo.Text = "";
            this.txtDVT.Text = "";
            this.txtDonGia.Text = "";
            this.txtVAT.Text = "";
        }

        private void getBy_MaVach_TonKhoDuoc()
        {
            BC.ZD_DM_THUOCBC bc = new ZD_DM_THUOCBC();
            DataTable dt = new DataTable();
            dt = bc.Get_TonKhoThuoc(this.txtMaVach.Text);
            if (dt.Rows.Count > 0)
            {
                this.txtTonKho.Text = dt.Rows[0][0].ToString();
            }
            else
            {
                this.txtTonKho.Text = "";
            }
        }

        private void txtSL_TextChanged(object sender, EventArgs e)
        {
            //this.tinhGia();
        }

        private void tinhGia()
        {
            //400 + 5*400/100
            Double sl;
            Double dg;
            Double vat;
            Double tt;

            try
            {
                sl = Double.Parse(this.txtSL.Text);
                dg = Double.Parse(this.txtDonGia.Text);
                vat = Double.Parse(this.txtVAT.Text);

                //tt = (sl * dg) + (sl * dg) * vat / 100;
                tt = (sl * dg);
                //String.Format("{0:0,0 vnđ}", 20000000)
                this.txtDonGia.Text = String.Format("{0:0,0}", dg);
                this.txtThanhTien.Text = String.Format("{0:0,0}", tt);
            }
            catch (Exception)
            { }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            //if (DateTime.Compare(DateTime.Parse(this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["ngaylap"].Value.ToString()).AddDays(1), DateTime.Now) < 0)
            //{
            //    // nhập quá 24h --> không được xóa
            //    MessageBox.Show("không xóa");
            //}
            //else
            //{
            //    //nhập chưa tới 24h --> được xóa
            //    MessageBox.Show("xóa được");
            //}

            if (this.txtId.Text == "")
            {
                for (int i = this.dgvData.SelectedRows.Count - 1; i >= 0; i--)
                {
                    this.dgvData.Rows.RemoveAt(this.dgvData.SelectedRows[i].Index);
                }
            }
            else
            {
                //if (DateTime.Compare(DateTime.Parse(this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["ngaylap"].Value.ToString()).AddDays(1), DateTime.Now) < 0)
                //{
                //    // nhập quá 24h --> không được xóa
                //    MessageBox.Show("Phiếu nhập đã quá 24h nên không thể xóa được!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}
                /// đã nhập quá 15' nên không được xóa
                if (DateTime.Compare(DateTime.Parse(dgvLeft.CurrentRow.Cells["NgayLap"].Value.ToString()).AddMinutes(15), DateTime.Parse(this.getTimeServer2())) < 0)
                {
                    MessageBox.Show("Đã quá thời gian được phép xóa phiếu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    //nhập chưa tới 24h --> được xóa
                    //MessageBox.Show("xóa được");
                    //}
                    if (MessageBox.Show("Bạn có muốn xóa thuốc này không?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            ZD_PHIEUXUATKHOCTBC bc = new ZD_PHIEUXUATKHOCTBC();
                            bc.Delete(ZD_PHIEUXUATKHOCT.ZD_PHIEUXUATKHOCTFields.Id, this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["id1"].Value.ToString());
                            //MessageBox.Show("Xóa thành công !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception)
                        { }

                        for (int i = this.dgvData.SelectedRows.Count - 1; i >= 0; i--)
                        {
                            this.dgvData.Rows.RemoveAt(this.dgvData.SelectedRows[i].Index);
                        }
                    }
                    this.checkMaVach();
                    if (_err == 0)
                    {
                        this.txtMaVach.Enabled = true;
                        this.txtSL.Enabled = true;
                    }
                }
            }
            getTongGia();
        }

        private int checkMaVach()
        {
            _err = 0;
            try
            {
                for (int i = 0; i < dgvData.Rows.Count; i++)
                {
                    try
                    {
                        Int32.Parse(this.dgvData.Rows[i].Cells["mavach"].Value.ToString());
                    }
                    catch (Exception)
                    {
                        return _err++;
                    }

                    if (this.dgvData.Rows[i].Cells["mavach"].Value.ToString() == "")
                    {
                        return _err++;
                    }
                }
            }
            catch (Exception)
            { }
            return _err;
        }

       
        private void txtSL_KeyDown(object sender, KeyEventArgs e)
        {            
            if (e.KeyCode == Keys.Enter)
            {
                if (txtSL.Text.Trim().Length > 0)
                {
                    if (Int32.Parse(txtSL.Text) <= Int32.Parse(txtTon.Text))
                    {
                        this.tinhGia();
                        btnAdd_Click(sender, e);
                        setTab(this.txtMaVach, e);
                        this.txtMaVach.Focus();
                    }
                    else
                    {
                        MessageBox.Show("Số lượng không hợp lệ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtSL.Focus();
                        //this.tinhGia();
                        //btnAdd_Click(sender, e);
                        //setTab(this.txtMaVach, e);
                        //this.txtMaVach.Focus();
                    }
                }
            }
        }

        private void tinhGia2() // Tính giá khi thay đổi số lượng trên lưới
        {
            if (this.dgvData.Rows.Count > 0)
            {
                //400 + 5*400/100
                int sl;
                Double dg;
                Double vat;
                Double tt;

                try
                {
                    for (int i = 0; i < this.dgvData.Rows.Count; i++)
                    {
                        //sl = Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["soluong"].Value.ToString());
                        //dg = Double.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["donGia"].Value.ToString());
                        //vat = Double.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["vat"].Value.ToString());

                        sl = Int32.Parse(this.dgvData.Rows[i].Cells["soluong"].Value.ToString());
                        dg = Double.Parse(this.dgvData.Rows[i].Cells["donGia"].Value.ToString());
                        vat = Double.Parse(this.dgvData.Rows[i].Cells["vat"].Value.ToString());
                        
                        tt = (sl * dg);
                       // this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["thanhtien"].Value = String.Format("{0:0,0}", tt);
                        this.dgvData.Rows[i].Cells["thanhtien"].Value = String.Format("{0:0,0}", tt);
                    }
                }
                catch (Exception)
                {}
            }
            this.getTongGia();
            //this.txtDelegateTraLai_SL.Text = "";
        }

        private void txtTongTien_TextChanged(object sender, EventArgs e)
        {
            try
            {
                MySetStr(this.txtTenKH.Text, this.txtDiaChi.Text, this.txtTongTien.Text, this.txtKhachDua.Text);
                MySetDgv(this.dgvData);
            
                this.txtKhachDua.Text = "";
                this.txtTraLai.Text = "";
                this.lblBangChu.Text = DICHSO.XL_DOC_SO.DOC_SO_CHUOI(Double.Parse(this.txtTongTien.Text.ToString()), "đồng", "", 0);
            }
            catch (Exception)
            { }
        }

        private void txtMaVach_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void dgvData_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //string _tensp = this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tensp"].Value.ToString().Substring(0,this.dgvData.Rows[dgvData.CurrentRow.Index].Cells["tensp"].Value.ToString().IndexOf("("));
            //MessageBox.Show(_tensp);
            if (this.txtBacSiKeDon.Text != "")
            {
                try
                {
                    Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["mavach"].Value.ToString());
                    this.getBy_MaVach_BanTheoDon();
                    this.tinhGia2();
                }
                catch (Exception)
                {
                   // MessageBox.Show("Số lượng nhập vào không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                try
                {
                    if (Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["soluong"].Value.ToString()) < 0)
                    {
                        MessageBox.Show("Không được nhập âm!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.groupBox2.Enabled = false;
                        //this.dgvData.Columns.Clear(); 
                    }
                    Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["soluong"].Value.ToString());
                    this.tinhGia2();
                }
                catch (Exception)
                {
                    MessageBox.Show("Số lượng nhập vào không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.groupBox2.Enabled = false;
                    //this.dgvData.Columns.Clear(); 
                }
            }
            this.checkMaVach_SL();
            if (_err == 0)
            {
                //MessageBox.Show(checkSL().ToString());
                this.txtMaVach.Enabled = true;
                this.txtTenThuoc.Enabled = true;
                this.txtSL.Enabled = true;
            }
        }

        private void txtMaDon_TextChanged(object sender, EventArgs e)
        {
            //this.dgvData.Rows.Clear();
            //getDonBS();
            //if (this.txtBacSiKeDon.Text != "")
            //{
            //    dgvData.Columns["mavach"].ReadOnly = false;
            //    this.txtSID.Enabled = false;
            //    this.dateTimeSID.Enabled = false;
            //    this.txtMaVach.Enabled = false;
            //    this.txtSL.Enabled = false;
            //    this.txtTenThuoc.Enabled = false;

            //    this.txtTenKH.Enabled = false;
            //    this.txtDiaChi.Enabled = false;
            //    this.cboxGioiTinh.Enabled = false;
            //    this.txtDienThoai.Enabled = false;
            //}
            //else
            //{
            //    dgvData.Columns["mavach"].ReadOnly = true;
            //    this.txtSID.Enabled = true;
            //    this.dateTimeSID.Enabled = true;
            //    this.txtMaVach.Enabled = true;
            //    this.txtSL.Enabled = true;
            //    this.txtTenThuoc.Enabled = true;
                
            //}
        }
        private void getDonBS()
        {
            //int id = 28;// 
            try
            {
                string sql = "select * from hien_ViewDonThuocCT_BanLe where donthuocid='" + int.Parse(this.txtMaDon.Text) + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    //-----------------------------------Hiển thị đơn thuốc---------------------------------------                   
                    //for (int i = 0; i < dt.Rows.Count; i++)
                    //{
                    //    this.dgvData.Rows.Add("", dt.Rows[i]["tenvt"].ToString(), "", "", dt.Rows[i]["dvt"].ToString(), dt.Rows[i]["soluong"].ToString(), "0", "0", "0", "", this.txtMaDon.Text);
                    //}
                    //-----------------------------------Kết thúc hiển thị đơn---------------------------------------  
                    //this.dgvData.DataSource = dt;
                    this.txtBacSiKeDon.Text = dt.Rows[0]["manhanvien"].ToString();

                    this.dateTimeSID.Text = dt.Rows[0]["dateSID"].ToString();
                    this.txtSID.Text = dt.Rows[0]["SID"].ToString();
                    //this.txtMaVach.Focus();
                }
                else
                {
                    this.dgvData.Rows.Clear();
                    this.txtBacSiKeDon.Text = "";
                    this.txtSID.Text = "";
                    this.txtMaDon.Text = "";
                }
            }
            catch (Exception)
            {
                this.dgvData.Rows.Clear();
                this.txtBacSiKeDon.Text = "";
                this.txtSID.Text = "";
            }
        }

        private void txtMaDon_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtSL_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }


        private void txtKhachDua_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtMaDon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.dgvData.Rows.Clear();
                getDonBS();
                if (this.txtBacSiKeDon.Text != "")
                {
                    //dgvData.Columns["mavach"].ReadOnly = false;
                    //dgvData.Columns["soluong"].ReadOnly = false;
                    this.groupBox1.Enabled = false;
                    this.txtMaVach.Enabled = true;
                    this.txtSL.Enabled = true;
                    this.txtTenThuoc.Enabled = false;
                    //this.txtTenKH.Enabled = true;
                    //this.txtDiaChi.Enabled = true;
                    //this.txtDienThoai.Enabled = true;
                    setTab(txtMaVach, e);
                    txtSID_KeyDown(sender, e);

                }
                else
                {
                    //dgvData.Columns["mavach"].ReadOnly = true;
                    //dgvData.Columns["soluong"].ReadOnly = true;
                    this.txtSID.Enabled = true;
                    this.dateTimeSID.Enabled = true;
                    this.txtMaVach.Enabled = true;
                    this.txtSL.Enabled = true;
                    this.txtTenThuoc.Enabled = true;
                    setTab(this.dateTimeSID, e);
                }
            }
        }

        private void dateTimeSID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtSID, e);
            }
        }

        private void txtSID_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (this.txtSID.Text.Substring(0, 1) == "0")
                {
                    this.txtSID.Text = this.txtSID.Text.Substring(1);
                }
            }
            catch (Exception)
            { }
            if (this.txtSID.Text.Length == 7)
            {
                this.getInfoSID();//26092012
                setTab(this.txtMaVach, e);
            }
            else
            {
                this.txtTenKH.Text = "";
                this.txtTenKH.Enabled = true;
                this.txtDiaChi.Text = "";
                this.txtDiaChi.Enabled = true;
                this.txtDienThoai.Text = "";
                this.txtDienThoai.Enabled = true;
                this.cboxGioiTinh.Text = "Nam";
                this.cboxGioiTinh.Enabled = true;
                setTab(this.txtTenKH, e);
            }
        }

        private void txtTenKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtDiaChi, e);
            }
        }

        private void txtDiaChi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtMaVach, e);
            }
        }

        private void cboxGioiTinh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtDienThoai, e);
            }
        }

        private void txtDienThoai_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtMaVach, e);
            }
        }

        private void txtMaVach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (this.txtMaVach.Text != "")
                {
                    this.getBy_MaVach();
                    //this.getBy_MaVach_TonKhoDuoc();
                    txtTon.Text = getSLTon();
                    setTab(this.txtSL, e);

                    //lay so luong
                    dataGridView1.Rows.Clear();
                    if (txtTenThuoc.Text.Trim() != "")
                    {
                        btnMaVachKhac.Visible = true;
                        getByNameSearch();
                        getSLTonByTenVT();
                        if (dataGridView1.Rows.Count > 0)
                        {
                            MessageBox.Show("Mã cận date: " + "[ " + dataGridView1.Rows[0].Cells[0].Value.ToString() + " ]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            btnMaVachKhac.Text = "Mã vạch khác: " + dataGridView1.Rows[0].Cells[0].Value.ToString();
                            txtMaVach.Focus();
                            txtMaVach.SelectAll();
                        }
                        else
                        {
                            btnMaVachKhac.Text = "Mã vạch khác";
                        }
                    }
                    else
                    {
                        btnMaVachKhac.Visible = false;
                        MessageBox.Show("Không có mã vạch này", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtMaVach.Focus();
                        txtMaVach.SelectAll();
                    }
                }
            }
        }

        private void getByNameSearch()
        {
            string sql1 = "SELECT zdp.mavach, zdp.hansd FROM zD_PHIEUNHAPKHOCT zdp " +
                            "INNER JOIN zD_PHIEUNHAPKHO zdp2 ON zdp2.sophieu = zdp.sophieu " +
                            "INNER JOIN zD_DM_THUOC zddt ON zddt.mavt = zdp.mavt " +
                            "WHERE zddt.NameSearch LIKE '%" + txtTenThuoc.Text + "%' " +
                            "AND CONVERT(DATETIME, zdp2.ngaylap, 103) > CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103) " +
                            "AND zdp.hansd < CONVERT(DATETIME, '" + txtHanDung.Text + "', 103)";
            //"ORDER BY zdp.hansd";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql1).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dataGridView1.Rows.Add(dt.Rows[i]["MaVach"], "", dt.Rows[i]["HanSD"]);
            }
        }

        private void getSLTonByTenVT()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                sql = "SELECT(( SELECT ISNULL(SUM(zdp.soluong), 0) AS SLNhap " +
                            "FROM zD_PHIEUNHAPKHOCT zdp INNER JOIN zD_PHIEUNHAPKHO zdp2 " +
                            "ON zdp2.sophieu = zdp.sophieu " +
                            "WHERE zdp2.huy = 0 AND  zdp.mavach = " + dataGridView1.Rows[i].Cells["MaVach1"].Value.ToString() + " AND CONVERT(DATETIME, zdp2.ngaylap, 103) > CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103)) + " +

                            "(SELECT ISNULL(sum(zdk.soluong), 0) FROM zD_KIEMKE2012 zdk " +
                            "WHERE zdk.mavach = " + dataGridView1.Rows[i].Cells["MaVach1"].Value.ToString() + " AND zdk.thang = " + DateTime.Now.Month + " AND zdk.nam = 2013) - " +

                            "(SELECT ISNULL(sum(zdp.soluong), 0) AS SLXuat " +
                            "FROM zD_PHIEUXUATKHOCT zdp INNER JOIN zD_PHIEUXUATKHO zdp2 " +
                            "ON zdp2.sophieu = zdp.sophieu " +
                            "WHERE zdp2.huy = 0 AND  zdp.mavach = " + dataGridView1.Rows[i].Cells["MaVach1"].Value.ToString() + "  and CONVERT(DATETIME, zdp2.ngaylap, 103) > CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103)) +" +
                            
                            "(SELECT ISNULL(SUM(zdptlc.SoLuongTraLai), 0) AS SLTra FROM zD_PhieuTraLaiCT zdptlc " +
                            "INNER JOIN zD_PhieuTraLai zdptl ON zdptl.SoHoaDonBanLe = zdptlc.SoHoaDonBanLe " +
                            "WHERE zdptlc.MaVach = " + dataGridView1.Rows[i].Cells["MaVach1"].Value.ToString() + " and CONVERT(DATETIME, zdptl.ngaylap, 103) > " +
                            "CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103)) " +
                            ") AS SL";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                this.dataGridView1.Rows[i].Cells["SoLuong1"].Value = dt.Rows[0][0].ToString();
            }
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                if (Int32.Parse(dataGridView1.Rows[i].Cells["SoLuong1"].Value.ToString()) < 0)
                {
                    this.dataGridView1.Rows.RemoveAt(this.dataGridView1.Rows[i].Index);
                }
            }
        }

        private string getSLTon()
        {
            string sql = "SELECT(( SELECT ISNULL(SUM(zdp.soluong), 0) AS SLNhap " +
                            "FROM zD_PHIEUNHAPKHOCT zdp INNER JOIN zD_PHIEUNHAPKHO zdp2 " +
                            "ON zdp2.sophieu = zdp.sophieu " +
                            "WHERE zdp2.huy = 0 AND zdp.mavach = " + txtMaVach.Text + " AND CONVERT(DATETIME, zdp2.ngaylap, 103) > CONVERT(DATETIME, '01/"+DateTime.Now.Month+"/2013 00:00:00', 103)) + " +
                             
                            "(SELECT ISNULL(sum(zdk.soluong), 0) FROM zD_KIEMKE2012 zdk " +
                            "WHERE zdk.mavach = " + txtMaVach.Text + " AND zdk.thang = "+DateTime.Now.Month+" AND zdk.nam = 2013) - " +
                             
                            "(SELECT ISNULL(sum(zdp.soluong), 0) AS SLXuat " +
                            "FROM zD_PHIEUXUATKHOCT zdp INNER JOIN zD_PHIEUXUATKHO zdp2 " +
                            "ON zdp2.sophieu = zdp.sophieu " +
                            "WHERE zdp2.huy = 0 AND zdp.mavach = " + txtMaVach.Text + "  and CONVERT(DATETIME, zdp2.ngaylap, 103) > CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103)) +" +
                            
                            "(SELECT ISNULL(SUM(zdptlc.SoLuongTraLai), 0) AS SLTra FROM zD_PhieuTraLaiCT zdptlc " +
		                    "INNER JOIN zD_PhieuTraLai zdptl ON zdptl.SoHoaDonBanLe = zdptlc.SoHoaDonBanLe " +
                            "WHERE zdptlc.MaVach = " + txtMaVach.Text + " and CONVERT(DATETIME, zdptl.ngaylap, 103) > " +
                            "CONVERT(DATETIME, '01/" + DateTime.Now.Month + "/2013 00:00:00', 103)) " +
                            ") AS SL";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];

            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString();
            }
            else
            {
                return "";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.txtMaDon.Enabled = true;
            this.txtMaDon.Text = "";;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.loadSoPhieu();
        }

        private void dgvLeft_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.clear1();
            getTimeBy_SoPhieu();
            hide_viewDonHang();
            selectTheoDoiBan();
            this.tinhGia2();
            getByMaDon();
        }

        private void selectTheoDoiBan()
        {
            try
            {
                this.dgvData.Rows.Clear();
                string sql = "select * from hien_TheoDoiBan where sophieu='" + this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString() + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                //this.dgvData.DataSource = dt;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //hiển thị ra lưới
                    this.dgvData.Rows.Add(dt.Rows[i]["mavach"].ToString(), dt.Rows[i]["tenvt"].ToString() + "(" + dt.Rows[i]["Infoinclude"].ToString() + ")", "", dt.Rows[i]["solo"].ToString(), dt.Rows[i]["ten"].ToString(), dt.Rows[i]["soluong"].ToString(), String.Format("{0:0,0}", dt.Rows[i]["dongia"]), dt.Rows[i]["vat"].ToString(), String.Format("{0:0,0}", dt.Rows[i]["thanhtien"].ToString()), dt.Rows[i]["mavt"].ToString(), dt.Rows[i]["traLai"].ToString(), dt.Rows[i]["donthuocid"].ToString(), dt.Rows[i]["id"].ToString());
                    
                }
                this.txtLoaiPhieu.Text = dt.Rows[0]["loaiPhieu"].ToString();
                this.txtNhanVien.Text = dt.Rows[0]["manhanvien"].ToString();
            }
            catch { }
        }

        private void hide_viewDonHang() //Ẩn các trường khi xem đơn hàng
        {
            this.groupBox1.Enabled = false;
            this.groupBox2.Enabled = false;
            this.panel3.Enabled = false;
            this.dgvData.Enabled = false;
        }

        private void getByMaDon() //Lấy ma đơn từ dgv đưa lên trên
        {
            this.txtId.Text = dgvLeft.Rows[dgvLeft.CurrentRow.Index].Cells["id"].Value.ToString();
            for (int i = 0; i < dgvData.Rows.Count; i++)
            {
                if (dgvData.Rows[i].Cells["donthuocid"].Value.ToString() != "")
                {
                    this.txtMaDon.Text = dgvData.Rows[i].Cells["donthuocid"].Value.ToString();
                    getTenBS();
                    getThongTinKH();
                    break;
                }
                else
                {
                    this.txtMaDon.Text = "";
                    getThongTinKH();
                }
            }
        }

        private void getTenBS()
        {
            try
            {
                string sql = "SELECT manhanvien FROM zD_DONTHUOC WHERE DonThuocId ='" + this.txtMaDon.Text + "'";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                this.txtBacSiKeDon.Text = dt.Rows[0]["manhanvien"].ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Lỗi getTenBS()");
            }
        }
        private void getThongTinKH()
        {
            string sql = "SELECT [SID], dateSID, hoten, diachi, dienthoai, gioitinh, ghichu FROM zD_PHIEUXUATKHO WHERE sophieu ='" + dgvLeft.Rows[dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString() + "'";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.txtSID.Text = dt.Rows[0]["SID"].ToString();
            this.dateTimeSID.Text = dt.Rows[0]["dateSID"].ToString();
            this.txtTenKH.Text = dt.Rows[0]["hoten"].ToString();
            this.txtDiaChi.Text = dt.Rows[0]["diachi"].ToString();
            this.txtDienThoai.Text = dt.Rows[0]["dienthoai"].ToString();
            if (Boolean.Parse(dt.Rows[0]["GioiTinh"].ToString()) == true)
            {
                this.cboxGioiTinh.Text = "Nam";
            }
            else
            {
                this.cboxGioiTinh.Text = "Nữ"; 
            }
            this.txtGhiChu.Text = dt.Rows[0]["Ghichu"].ToString();
        }

        public override void btnEdit_Click(object sender, EventArgs e)
        {
            base.btnEdit_Click(sender, e);
            DateTime s = DateTime.Parse(this.getTimeServer2());
            //so sanh thoi gian 15'
            if (DateTime.Compare(DateTime.Parse(dgvLeft.CurrentRow.Cells["NgayLap"].Value.ToString()).AddMinutes(15), DateTime.Parse(this.getTimeServer2())) < 0)
            {
                MessageBox.Show("Đã quá thời gian được phép sửa phiếu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                //MessageBox.Show("abc");
                this.cboxChonNgay.Visible = false;
                //this.dgvData.Columns["tralai"].Visible = true;

                if (this.txtId.Text != "")
                {
                    this.txtMaVach.Focus();
                    this.groupBox1.Enabled = true;
                    this.groupBox2.Enabled = true;
                    this.panel3.Enabled = true;
                    this.dgvData.Enabled = true;

                    this.itmSua.Visible = true;
                }
            }
        }

        public override void btnInPhieu_Click(object sender, EventArgs e)
        {
            base.btnInPhieu_Click(sender, e);

            string sql = "select * from hien_rpt_BanLe where sophieu='" + this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString() + "'";

            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            frmShowReport frm = new frmShowReport(2);
            frmShowReport._thanhtien = lblBangChu.Text;
            frmShowReport._nhanvien = this.txtNhanVien.Text;
            frmShowReport._tenKH = this.txtTenKH.Text;
            frmShowReport._diachiKH = this.txtDiaChi.Text;
            frmShowReport._dt = dt;
            frmShowReport.strC = frmShowReport.BC.HOADONBANLE;
            frm.ShowDialog();
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //this.dgvLeft.Rows.Clear();
                //string sql = "SELECT distinct sophieu, id, ngaylap FROM hien_SearchDonHang WHERE hoten LIKE N'" + "%" + this.txtSearch.Text + "%' OR diachi LIKE N'" + "%" + this.txtSearch.Text + "%' OR tenvt LIKE N'" + "%" + this.txtSearch.Text + "%' GROUP BY sophieu, id, ngaylap ORDER BY id desc,sophieu, ngaylap";
                string sql = "SELECT distinct sophieu, id, ngaylap FROM hien_SearchDonHang WHERE loaiphieu = '"+_loaiPhieu+"' and huy = 0 and ( hoten LIKE N'" + 
                    "%" + this.txtSearch.Text + "%' OR diachi LIKE N'" + "%" + this.txtSearch.Text + "%' OR tenvt LIKE N'" +
                    "%" + this.txtSearch.Text + "%') AND ngaylap BETWEEN CONVERT(DATETIME,'" + this.date1.Text +
                    " 00:00:00', 103)AND CONVERT(DATETIME,'" + this.date2.Text + " 23:59:00', 103)" +
                    " GROUP BY sophieu, id, ngaylap ORDER BY id desc,sophieu, ngaylap";
                DataTable dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                this.dgvLeft.DataSource = dt;
                this.btnSoLuong.Text = "Số lượng:" + dt.Rows.Count;
            }
        }

        private void dateTimeSID_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.txtSID.Text.Substring(0, 1) == "0")
                {
                    this.txtSID.Text = this.txtSID.Text.Substring(1);
                }
            }
            catch (Exception)
            { }
            if (this.txtSID.Text.Length == 7)
            {
                this.getInfoSID();//26092012
                //setTab(this.txtMaVach, e);
            }
            else
            {
                this.txtTenKH.Text = "";
                this.txtTenKH.Enabled = true;
                this.txtDiaChi.Text = "";
                this.txtDiaChi.Enabled = true;
                this.txtDienThoai.Text = "";
                this.txtDienThoai.Enabled = true;
                this.cboxGioiTinh.Text = "Nam";
                this.cboxGioiTinh.Enabled = true;
                //setTab(this.txtTenKH, e);
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            frmTK_DoanhThu frm = new frmTK_DoanhThu(_loaiPhieu);
            frm.ShowDialog();
        }

        private void dgvLeft_KeyDown(object sender, KeyEventArgs e)
        {
            this.clear1();
            hide_viewDonHang();
            selectTheoDoiBan();
            this.tinhGia2();
            getByMaDon();
        }

        private void dgvLeft_KeyUp(object sender, KeyEventArgs e)
        {
            this.clear1();
            hide_viewDonHang();
            selectTheoDoiBan();
            this.tinhGia2();
            getByMaDon();
        }

        private void txtTenKH_TextChanged(object sender, EventArgs e)
        {
            try
            {
                MySetStr(this.txtTenKH.Text, this.txtDiaChi.Text, this.txtTongTien.Text, this.txtKhachDua.Text);
                MySetDgv(this.dgvData);
            }
            catch (Exception)
            { }
        }

        private void txtDiaChi_TextChanged(object sender, EventArgs e)
        {
            try
            {
                MySetStr(this.txtTenKH.Text, this.txtDiaChi.Text, this.txtTongTien.Text, this.txtKhachDua.Text);
                MySetDgv(this.dgvData);
            }
            catch (Exception)
            { }
        }

        private void frmHD_BanLe_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void txtSearch_MouseClick(object sender, MouseEventArgs e)
        {
            this.txtSearch.Text = "";
        }

        public override void btnHuyPhieu_Click(object sender, EventArgs e)
        {
            if (checkExitSoPhieu() == false)
            {
                if (dgvData.Rows.Count > 0)
                {
                    base.btnHuyPhieu_Click(sender, e);
                    if (DateTime.Compare(DateTime.Parse(dgvLeft.CurrentRow.Cells["NgayLap"].Value.ToString()).AddHours(12), DateTime.Parse(this.getTimeServer2())) < 0)
                    {
                        MessageBox.Show("Đã quá thời gian được phép xóa phiếu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        if (MessageBox.Show("Bạn có muốn hủy phiếu này không?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            Base.frmHuyPhieu f = new ModuleDuoc.Base.frmHuyPhieu();
                            f.MyGetData = new ModuleDuoc.Base.frmHuyPhieu.GetString(GetValue);
                            f.ShowDialog();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Phiếu này đã được tạo nên không thể xóa được!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        private bool checkExitSoPhieu()
        {
            string sql = "SELECT * FROM [QUANLYVTXN].[thongke].[hien_rpt_TraLai] " +
                         "WHERE SoHoaDonBanLe = N'" + dgvLeft.CurrentRow.Cells["SoPhieu"].Value.ToString() + "'";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return true;
            }
            else
            { return false; }
        }

        private void huyHoaDon()
        {
            string sql = "UPDATE zD_PHIEUXUATKHO SET ghichu = '"+this.txtDelegate.Text+"',huy = 1, manhanvien = '"+_tennhanvien+"' WHERE sophieu ='"+this.dgvLeft.Rows[this.dgvLeft.CurrentRow.Index].Cells["SoPhieu"].Value.ToString()+"'";
            SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql);
            MessageBox.Show("Hủy phiếu thành công", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            huyHoaDon();
            this.loadSoPhieu();
            this.dgvData.Rows.Clear();
        }

        //private void itmSua_Click(object sender, EventArgs e)
        //{
        //    if (MessageBox.Show("Bạn có muốn sửa không?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        //    {
        //        frmTraLai f = new frmTraLai();
        //        f.MySetData = new frmTraLai.SetString(GetTraLai);
        //        f.ShowDialog();
        //    }
        //}

        //private void txtDelegateTraLai_SL_TextChanged(object sender, EventArgs e)
        //{
        //    this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["TraLai"].Value = Int32.Parse(this.txtDelegateTraLai_SL.Text);
        //    this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["SoLuong"].Value = Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["soluong"].Value.ToString()) + Int32.Parse(this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["TraLai"].Value.ToString());
        //    this.tinhGia2();
        //    this.txtDelegateTraLai_SL.Text = "0";
        //}

        private void dgvData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //try
            //{
            //    this.label25.Visible = false;
            //    for (int i = 0; i < this.dgvData.Rows.Count; i++)
            //    {
            //        if (Convert.ToInt32(this.dgvData.Rows[i].Cells["traLai"].Value.ToString()) != 0)
            //        {
            //            this.dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
            //            this.label25.Visible = true;
            //        }
            //    }
            //}
            //catch { }
        }

        //private void dgvData_KeyDown(object sender, KeyEventArgs e)
        //{
        //    setTab(this.dgvLeft, e);
        //}

        //private void dgvData_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
        //        e.Handled = true;
        //}

        //Phan quyen tren nut
        private Dictionary<string, bool> getPermission(string formName, string username)
        {
            string sql = "select * from zD_Permission where FormName='" + formName + "' and UserName='" + username + "'";
            System.Data.DataTable dt = SqlHelper.ExecuteDataset(
                System.Configuration.ConfigurationManager.AppSettings["Main.ConnectionString"],
                System.Data.CommandType.Text,
                sql).Tables[0];
            Dictionary<string, bool> per = new Dictionary<string, bool>();
            if (dt.Rows.Count > 0)
            {
                per.Add("Add", bool.Parse(dt.Rows[0]["AddA"].ToString()));
                per.Add("Edit", bool.Parse(dt.Rows[0]["EditA"].ToString()));
                per.Add("Delete", bool.Parse(dt.Rows[0]["DeleteA"].ToString()));
                per.Add("Print", bool.Parse(dt.Rows[0]["PrintA"].ToString()));
                per.Add("Export", bool.Parse(dt.Rows[0]["ExportA"].ToString()));
            }
            return per;
        }
        private void setPermission()
        {
            //Dictionary<string, bool> _per = getPermission(this.Name, _manv);

            //this.btnThemMoi.Enabled = _per["Add"];
            //this.btnEdit.Enabled = _per["Edit"];
            //this.btnHuyPhieu.Enabled = _per["Delete"];
            //this.btnInPhieu.Enabled = _per["Print"];
        }

        private void itmSua_Click(object sender, EventArgs e)
        {
            //if (DateTime.Compare(DateTime.Parse(dgvLeft.CurrentRow.Cells["NgayLap"].Value.ToString()).AddHours(12), DateTime.Parse(this.getTimeServer2())) < 0)
            //{
            //    MessageBox.Show("Đã quá thời gian được phép trả lại phiếu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
            //else
            {
                frmPhieuTraLai f = new frmPhieuTraLai(txtTenKH.Text, txtDienThoai.Text, txtDiaChi.Text, _tennhanvien, dgvLeft.Rows[dgvLeft.CurrentRow.Index].Cells["sophieu"].Value.ToString());
                f.ShowDialog();
            }
        }

        private void cboxChonNgay_ValueChanged(object sender, EventArgs e)
        {
            if (DateTime.Compare(DateTime.Parse(this.cboxChonNgay.Text), DateTime.Parse(String.Format("{0:dd/MM/yyyy}", DateTime.Now))) < 0)
            {
                MessageBox.Show("Bạn đã chọn ngày nhỏ hơn ngày hiện tại", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (DateTime.Compare(DateTime.Parse(this.cboxChonNgay.Text), DateTime.Parse(String.Format("{0:dd/MM/yyyy}", DateTime.Now))) > 0)
            {
                MessageBox.Show("Bạn đã chọn ngày lớn hơn ngày hiện tại", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void radBanLe_CheckedChanged(object sender, EventArgs e)
        {
            label24.Text = "Khách hàng"; 
            label4.Text = "Địa chỉ";
            _loaiPhieu = "3";
        }

        private void radtNoiBo_CheckedChanged(object sender, EventArgs e)
        {
            label24.Text = "Người nhận";
            label4.Text = "Khoa phòng";
            _loaiPhieu = "4";
        }

        private void radBaoHiem_CheckedChanged(object sender, EventArgs e)
        {
            label24.Text = "Họ và tên";
            label4.Text = "Mã thẻ BHYT";
            _loaiPhieu = "5";
        }

        private void btnMaVachKhac_Click(object sender, EventArgs e)
        {
            if (txtMaVach.Text.Length > 0)
            {
                frmMaVachKhac f = new frmMaVachKhac(txtTenThuoc.Text);
                f.ShowDialog();
            }
            else
            {
                MessageBox.Show("Không có mã vạch", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtMaVach.Focus();
            }
        }

        private void btnXuatThuocBH_Click(object sender, EventArgs e)
        {
            {
                frmXuatThuocBH f = new frmXuatThuocBH();
                f.ShowDialog();
            }
        }

        private void txtTenThuoc_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            setMaVach();
            string sql = "SELECT CONVERT(VARCHAR(10), mavach)AS ma, solo" +
                           " FROM zD_MaVach";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            frmShowReport frm = new frmShowReport(2);
            //frmShowReport._thanhtien = lblBangChu.Text;
            //frmShowReport._nhanvien = _tennhanvien;
            //frmShowReport._tenKH = this.txtTenKH.Text;
            //frmShowReport._diachiKH = this.txtDiaChi.Text;
            frmShowReport._dt = dt;
            frmShowReport.strC = frmShowReport.BC.InMaVach;
            frm.ShowDialog();
        }

        private void setMaVach() // insert so luong ma vach muon in ra
        {
            num1 = 0;
            num2 = 0;
            string sql = "SELECT zdp2.mavach, zdp2.solo, zdp2.soluong FROM zD_PHIEUXUATKHO zdp " +
                            "INNER JOIN zD_PHIEUXUATKHOCT zdp2 ON zdp2.sophieu = zdp.sophieu " +
                            "WHERE zdp.sophieu = '"+dgvLeft.CurrentRow.Cells["SoPhieu"].Value.ToString()+"'";
            DataTable dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];

            if (dt.Rows.Count > 0)
            {
                //Cap nhat va vach muon in
                string sql1 = "TRUNCATE TABLE zD_MaVach";
                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql1);
                for (num1 = 0; num1 < dt.Rows.Count; num1++)
                {
                    for (num2 = 0; num2 < int.Parse(dt.Rows[num1]["soluong"].ToString()); num2++)
                    {
                        string sql2 = "INSERT INTO [QUANLYVTXN].[dbo].[zD_MaVach]([mavach] ,[solo]) " +
                                      "VALUES('" + dt.Rows[num1]["mavach"].ToString() + "', '" + dt.Rows[num1]["solo"].ToString() + "')";
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql2);
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Report.frmTK_TongHopTonKho_AT f = new ModuleDuoc.Report.frmTK_TongHopTonKho_AT();
            f.Show();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (txtTenThuoc.Text.Trim().Length > 0)
            {
                frmKiemKe1 f = new frmKiemKe1(txtMaVach.Text);
                f.ShowDialog();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DM.frmTheKho_New f = new ModuleDuoc.DM.frmTheKho_New(txtMaVach.Text.Trim());
            f.Show();
        }
    }
}


